#include "audio_decoder.h"

static esp_audio_dec_handle_t decoder;

void decoder_task(void *args);
my_decoder_t my_decoder;
void audio_decoder_init()
{

    esp_opus_dec_cfg_t opus_cfg = {
        .sample_rate = 16000,
        .channel = 1,
        .frame_duration = ESP_OPUS_DEC_FRAME_DURATION_60_MS,
        .self_delimited = false};
    esp_opus_dec_open(&opus_cfg, sizeof(opus_cfg), &decoder);
}

void audio_decoder_start(RingbufHandle_t rb)
{

    my_decoder.is_running = true;
    my_decoder.inputBuf = rb;
    xTaskCreatePinnedToCoreWithCaps(&decoder_task, "decoder_task", 64 * 1024, NULL, 5, NULL, 0, MALLOC_CAP_SPIRAM);
}

void decoder_task(void *args)
{
    esp_audio_dec_in_raw_t in_frame;
    memset(&in_frame, 0, sizeof(esp_audio_dec_in_raw_t));
    esp_audio_dec_out_frame_t out_frame;
    out_frame.buffer = heap_caps_malloc(8 * 1024, MALLOC_CAP_SPIRAM);
    out_frame.len = 8 * 1024;

    while (my_decoder.is_running)
    {

        in_frame.buffer = xRingbufferReceive(my_decoder.inputBuf, &in_frame.len, portMAX_DELAY);

        void *raw_buffer = in_frame.buffer; // 记录缓冲区数据的原始地址, 用于后期归还
        while (in_frame.len > 0)
        {

            esp_audio_dec_info_t aud_info;
            esp_opus_dec_decode(decoder, &in_frame, &out_frame, &aud_info);

            bsp_sound_write(out_frame.buffer, out_frame.decoded_size);
            in_frame.buffer += in_frame.consumed;
            in_frame.len -= in_frame.consumed;
        }
        vRingbufferReturnItem(my_decoder.inputBuf, raw_buffer);
    }

    esp_opus_dec_close(decoder);
    vTaskDelete(NULL);
}